#pragma once
#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>
#include <vector>
using namespace std;
class SelectServ
{
    public:
        SelectServ()
        {
            max_fd_ = -1;
            FD_ZERO(&readfds_);
        }
        ~SelectServ()
        {

        }
        //添加文件描述符
        void Addfd(int fd)
        {
            FD_SET(fd,&readfds_);
            //更新最大描述符的值
            if(fd > max_fd_)
            {
                max_fd_ = fd;
            }
        }
        //删除在可读集合的描述符
        void Delete(int fd)
        {
            FD_CLR(fd,&readfds_);
            //更新最大描述符的值
            for(int i = max_fd_; i >= 0;i-- )
            {
                if(FD_ISSET(i,&readfds_))
                {
                    max_fd_ = i;
                    break;
                }
            }
        }
        //监视
        int Select(vector<int>* vec, struct timeval* tv = NULL)
        {
            fd_set tmp = readfds_;
            int ret = select(max_fd_+1,&tmp,NULL,NULL,tv);
            if(ret < 0)
            {
                perror("select");
                return -1;
            }
            else if(ret == 0)
            {
                printf("timeout");
                return 0;
            }
            //正常监控了
            for(int i = 0;i <= max_fd_;i++)
            {
                if(FD_ISSET(i,&tmp))
                {
                    vec->push_back(i);
                }
            }
            return ret;
        }

    private:
        //文件描述符的最大数
        int max_fd_;
        //保存可读事件集
        fd_set readfds_;
};
